package com.loong.common.nacos;

import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;

@Slf4j
@Component
public class DynamicKey {


    private final static String dataId = "dynamic-key";

    @Autowired
    private NacosConfigProperties properties;

    private Map<String, Object> dynamicMap = new HashMap<>();

    /**
     * 获取配置设置的值
     *
     * @param key
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T getDynamicValue(final String key, Class<T> clazz) {
        if (dynamicMap.containsKey(key) == false) {
            return null;
        }
        JSONObject obj = (JSONObject) dynamicMap.get(key);
        if (ObjectUtils.isEmpty(obj)) {
            return null;
        }
        return obj.toJavaObject(clazz);
    }

    @PostConstruct
    private void init() {
        try {
            ConfigService configService = NacosFactory.createConfigService(properties.getServerAddr());
            configService.addListener(dataId, properties.getGroup(), new DataSourceListener());
            String source = configService.getConfig(dataId, properties.getGroup(), properties.getTimeout());
            setDataSource(source);
        } catch (NacosException e) {
            log.error("DynamicKey.init()", e);
        }
    }

    class DataSourceListener implements Listener {

        @Override
        public Executor getExecutor() {
            return null;
        }

        @Override
        public void receiveConfigInfo(String configInfo) {
            setDataSource(configInfo);
        }

    }

    private void setDataSource(final String source) {
        if (StringUtils.isEmpty(source)) {
            return;
        }
        dynamicMap.clear();
        JSONArray dataArray = JSON.parseArray(source);
        JSONObject dataObj;
        String key;
        for (int i = 0, len = dataArray.size(); i < len; i++) {
            dataObj = dataArray.getJSONObject(i);
            if (dataObj.containsKey("key") == false) {
                continue;
            }
            key = dataObj.getString("key");
            dynamicMap.put(key, dataObj.get("value"));
        }
    }

}
